package com.ztom.top100;

import java.util.ArrayList;
import java.util.List;

/**
 * 生成括号
 * <p>
 * https://leetcode-cn.com/problems/generate-parentheses/
 *
 * @author ZhangTao
 */
public class Code13GenerateParenthesis {

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        if (n == 0) {
            return res;
        }
        if (n == 1) {
            res.add("()");
            return res;
        }

        process(res, 0, 0, n, new StringBuilder());

        return res;
    }

    private void process(List<String> res, int lCount, int rCount, int n, StringBuilder builder) {
        // 剪枝: 括号超出 n, 或者左括号数居然小于右括号数
        if (lCount > n || rCount > n || lCount < rCount) {
            return;
        }
        if (lCount == n && rCount == n) {
            res.add(builder.toString());
            return;
        }
        process(res, lCount + 1, rCount, n, builder.append("("));
        // 回溯时恢复现场
        builder.deleteCharAt(builder.length() - 1);
        process(res, lCount, rCount + 1, n, builder.append(")"));
        builder.deleteCharAt(builder.length() - 1);
    }
}
